require('./bootstrap');
const LazyLoad = require('vanilla-lazyload');
const justifiedLayout = require('justified-layout');

window.justifiedLayout =  justifiedLayout
Turbolinks.start()

var lazyLoadInstance = new LazyLoad({
    threshold: 300,
})

window.layoutPicture = function (archive) {
    var element = '#archive-' + archive.id
    var items = archive.files.map(file => {
        return {
            width: file.width,
            height: file.height
        }
    })
    var containerWidth = $(element).width();
    var result = justifiedLayout(items, {
        targetRowHeight: 220,
        showWidows: true,
        containerWidth,
    })
    $(element).css({
        height: result.containerHeight + 'px'
    })

    result.boxes.forEach((i, index) => {
        $(element).find('div:eq(' + index + ')').css({
            top: i.top + 'px',
            left: i.left + 'px',
            width: i.width + 'px',
            height: i.height + 'px'
        }).find('img').css({
            width: i.width + 'px',
            height: i.height + 'px'
        })
    })
}
window.layoutPictures = function (data) {
    data.forEach(d => layoutPicture(d))
}
window.layoutAll = function () {
    try {
        archives && layoutPictures(archives.data)
    } catch(e) {}
    try {
        archive && layoutPicture(archive)
    } catch(e) {}
    lazyLoadInstance.update()
}
window.addEventListener('DOMContentLoaded', layoutAll)
document.addEventListener("turbolinks:load", layoutAll)

